import {
  AlipayOutlined,
  LockOutlined,
  MobileOutlined,
  TaobaoOutlined,
  UserOutlined,
  WeiboOutlined,
} from '@ant-design/icons';
import {
  LoginFormPage,
  ProConfigProvider,
  ProFormCaptcha,
  ProFormCheckbox,
  ProFormText,
} from '@ant-design/pro-components';
import { Button, Divider, Space, Tabs, message, theme,Modal,Form,Input } from 'antd';
import type { CSSProperties } from 'react';
import React, { useRef, useState,useEffect } from 'react';
import { useIntl ,history,useModel,useParams} from '@umijs/max';
import { useLocation } from 'react-router-dom';
import { getGlobalApp } from '@/utils/format';
import services from '@/services/home';
const { getAuthLogin,resetPassWord,getAuthInfo,loginDingDing} =
  services.UserController;
import styles from './index.less';

type LoginType = 'phone' | 'account'| 'dingding';

const iconStyles: CSSProperties = {
  color: 'rgba(0, 0, 0, 0.2)',
  fontSize: '18px',
  verticalAlign: 'middle',
  cursor: 'pointer',
};

const Page = () => {
  const [loginType, setLoginType] = useState<LoginType>('account');
  const { allToken,setLoginToken } = useModel('global');
  const { initialState, setInitialState }:any = useModel('@@initialState');
  const [loginInfo, setLoginInfo] = useState({} as any);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const { token } = theme.useToken();
  const location = useLocation();  
  const queryParams = new URLSearchParams(location.search);  
  

  const [formLogin] = Form.useForm();
  const formItemLayout = {
    labelCol: {
      xs: { span: 24 },
      sm: { span: 8 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 16 },
    },
  };
  const tabsItems:any = [
    { key: 'account', label: '账号密码登录'},
    { key: 'dingding', label: '钉钉登录'},
    // { key: 'phone', label: '手机号登录'},
  ];

   useEffect(() => { 
    const _authCode = queryParams.get('authCode'); // 获取名为 'myParam' 的查询参数
    console.log('===_params===',_authCode,location)
    if(_authCode){
      setLoading(true);
      loginDingDing({
        authCode: _authCode,
      }).then((_res:any)=>{
        setLoading(false);
        if(_res.appCode == 'S0000'){
          setLoginToken(_res.result?.token);
          getUserInfo(_res.result.token);
        }else{
          message.error(_res.appMesg || '失败，请重试');
        }
      });
     
    }
  }, []);
 
   useEffect(() => { 
   // STEP3：在需要的时候，调用 window.DTFrameLogin 方法构造登录二维码，并处理登录成功或失败的回调。
  //  response_type=code&client_id=ding3gxexs8wosaiun1i&scope=openid&prompt=consent`,
  if(loginType == 'dingding'){
    (window as any).DTFrameLogin(
      {
          id: 'self_defined_element',
          width: 300,
          height: 300,
      },
      {
          redirect_uri: encodeURIComponent(window.location.origin+""+window.location.pathname),
          client_id: 'dingrv5shkogdeaucex0',
          scope: 'openid',
          response_type: 'code',
          // state: 'xxxxxxxxx',
          prompt: 'consent',
      },
      (loginResult:any) => {
          const {redirectUrl, authCode, state} = loginResult;
          // 这里可以直接进行重定向
          window.location.href = redirectUrl;
          // 也可以在不跳转页面的情况下，使用code进行授权
          console.log(authCode);
      },
      (errorMsg:any) => {
          // 这里一般需要展示登录失败的具体原因,可以使用toast等轻提示
          console.error(`errorMsg of errorCbk: ${errorMsg}`);
      },
    );
  }
  }, [loginType]);
   
  const handleOk =  (e: React.MouseEvent<HTMLElement>) => {
    console.log(e);
    setLoading(true);
    formLogin.validateFields().then(async (values:any) => {
      const _res = await resetPassWord({
        username:loginInfo?.username,
        password:loginInfo?.password,
        newPassWord:values.password
      });
      setLoading(false);
      console.log('values==',_res,values);
      if(_res.appCode == 'S0000'){
        message.success('修改成功');
        // history.push('/');
        getUserInfo(allToken);
      }else{
        message.error(_res.appMesg || '失败，请重试');
      }
    })
    .catch((errorInfo:any) => {
      setLoading(false);
      // console.log('errorInfo==',errorInfo);
    });
    // setIsModalOpen(false);
 
  };

  const handleCancel = (e: React.MouseEvent<HTMLElement>) => {
    console.log(e);
    setIsModalOpen(false);
  };

  const getUserInfo = async (values:any)=>{
    const hide = message.loading('获取用户信息');
    try {
      const _res = await getAuthInfo();
      console.log('=======login==',values,_res);
      hide();
      if(_res.appCode == 'S0000'){
        const _flist =  getGlobalApp().filter((_gl)=>{
          return _res.result?.menus.some((_si:any)=>_si.name == _gl.name);
        });
        const _applist =  _res.result?.apps.filter((_gl:any)=>{
          return getGlobalApp().some((_si:any)=>_si.name == _gl.code);
        });
        setInitialState((s:any) => (
          { ...s,
            fetchUserInfo: _flist, 
            appList: _applist, 
            extApps: _res.result?.extApps  || [], 
            currentUser: _res.result?.user,
            menuList:_res.result?.menus 
          }
        ));
        message.success('登录成功');
        setTimeout(()=>{
          // history.push('/');
          history.push('/tcpi/index');
        });
      }else{
        message.error(_res.appMesg || '失败，请重试');
      }
      
    } catch (error) {
      // hide();
      console.log('=======login error==',error);
      message.error('失败，请重试');
    }
    // history.push('/');
  };

  const onFinish = async (values:any)=>{
    
    const hide = message.loading('正在登录');
    try {
      const _res = await getAuthLogin(values);
      hide();
      console.log(values,_res);
      if(_res.appCode == 'S0000'){
        setLoginToken(_res.result?.token);
        if(_res.result?.resetPassWord == 1){
          message.error('第一次登录请重新配置密码');
          setIsModalOpen(true);
          setLoginInfo({
            username:values.username,
            password:values.password,
            token:_res.result?.token,
          });
        }else{
          // message.success('登录成功');
          getUserInfo(_res.result?.token);
          // history.push('/');
        }
      }else{
        message.error(_res.appMesg || '失败，请重试');
      }
    } catch (error) {
      hide();
      message.error('失败，请重试');
    }
    // history.push('/');
  };
 

  return (
    <div
      className='tc_cop_login_main'
      style={{
        backgroundColor: 'white',
        height: '100vh',
      }}
    >
      <LoginFormPage
        className={ loginType === 'dingding' ? 'tc_cop_login_1':'tc_cop_login_2'}
        backgroundImageUrl="https://mdn.alipayobjects.com/huamei_gcee1x/afts/img/A*y0ZTS6WLwvgAAAAAAAAAAAAADml6AQ/fmt.webp"
        // logo="https://github.githubassets.com/images/modules/logos_page/Octocat.png"
        backgroundVideoUrl="https://gw.alipayobjects.com/v/huamei_gcee1x/afts/video/jXRBRK_VAwoAAAAAAAAAAAAAK4eUAQBr"
        title="星卡协同办公平台"
        containerStyle={{
          backgroundColor: 'rgba(0, 0, 0,0.65)',
          backdropFilter: 'blur(4px)',
        }}
        onFinish={onFinish}
        // subTitle="星卡协同办公平台"
        // activityConfig={{
        //   style: {
        //     boxShadow: '0px 0px 8px rgba(0, 0, 0, 0.2)',
        //     color: token.colorTextHeading,
        //     borderRadius: 8,
        //     backgroundColor: 'rgba(255,255,255,0.25)',
        //     backdropFilter: 'blur(4px)',
        //   },
        //   title: '活动标题，可配置图片',
        //   subTitle: '活动介绍说明文字',
        //   action: (
        //     <Button
        //       size="large"
        //       style={{
        //         borderRadius: 20,
        //         background: token.colorBgElevated,
        //         color: token.colorPrimary,
        //         width: 120,
        //       }}
        //     >
        //       去看看
        //     </Button>
        //   ),
        // }}
        // actions={
        //   <div
        //     style={{
        //       display: 'flex',
        //       justifyContent: 'center',
        //       alignItems: 'center',
        //       flexDirection: 'column',
        //     }}
        //   >
        //     <Divider plain>
        //       <span
        //         style={{
        //           color: token.colorTextPlaceholder,
        //           fontWeight: 'normal',
        //           fontSize: 14,
        //         }}
        //       >
        //         其他登录方式
        //       </span>
        //     </Divider>
        //     <Space align="center" size={24}>
        //       <div
        //         style={{
        //           display: 'flex',
        //           justifyContent: 'center',
        //           alignItems: 'center',
        //           flexDirection: 'column',
        //           height: 40,
        //           width: 40,
        //           border: '1px solid ' + token.colorPrimaryBorder,
        //           borderRadius: '50%',
        //         }}
        //       >
        //         <AlipayOutlined style={{ ...iconStyles, color: '#1677FF' }} />
        //       </div>
        //       <div
        //         style={{
        //           display: 'flex',
        //           justifyContent: 'center',
        //           alignItems: 'center',
        //           flexDirection: 'column',
        //           height: 40,
        //           width: 40,
        //           border: '1px solid ' + token.colorPrimaryBorder,
        //           borderRadius: '50%',
        //         }}
        //       >
        //         <TaobaoOutlined style={{ ...iconStyles, color: '#FF6A10' }} />
        //       </div>
        //       <div
        //         style={{
        //           display: 'flex',
        //           justifyContent: 'center',
        //           alignItems: 'center',
        //           flexDirection: 'column',
        //           height: 40,
        //           width: 40,
        //           border: '1px solid ' + token.colorPrimaryBorder,
        //           borderRadius: '50%',
        //         }}
        //       >
        //         <WeiboOutlined style={{ ...iconStyles, color: '#1890ff' }} />
        //       </div>
        //     </Space>
        //   </div>
        // }
      >
        <Tabs
          centered
          activeKey={loginType}
          onChange={(activeKey) => setLoginType(activeKey as LoginType)}
          items={tabsItems}
        >
          {/* <Tabs.TabPane key={'account'} tab={'账号密码登录'} />
          <Tabs.TabPane key={'dingding'} tab={'钉钉登录'} /> */}
          {/* <Tabs.TabPane key={'phone'} tab={'手机号登录'} /> */}
        </Tabs>
        {loginType === 'account' && (
          <>
            <ProFormText
              name="username"
              fieldProps={{
                size: 'large',
                prefix: (
                  <UserOutlined
                    style={{
                      color: token.colorText,
                    }}
                    className={'prefixIcon'}
                  />
                ),
              }}
              placeholder={'用户名: 邮箱'}
              rules={[
                {
                  required: true,
                  message: '请输入用户名!',
                },
              ]}
            />
            <ProFormText.Password
              name="password"
              fieldProps={{
                size: 'large',
                prefix: (
                  <LockOutlined
                    style={{
                      color: token.colorText,
                    }}
                    className={'prefixIcon'}
                  />
                ),
              }}
              placeholder={'密码: 默认邮箱'}
              rules={[
                {
                  required: true,
                  message: '请输入密码！',
                },
              ]}
            />
          </>
        )}
        {loginType === 'dingding' && (
          <>
            <div>
            {/* <!-- STEP1：在HTML中添加包裹容器元素 --> */}
              <div id="self_defined_element" className={styles.self_defined_classname}></div>
            </div>
          </>
        )}
        {loginType === 'phone' && (
          <>
            <ProFormText
              fieldProps={{
                size: 'large',
                prefix: (
                  <MobileOutlined
                    style={{
                      color: token.colorText,
                    }}
                    className={'prefixIcon'}
                  />
                ),
              }}
              name="mobile"
              placeholder={'手机号'}
              rules={[
                {
                  required: true,
                  message: '请输入手机号！',
                },
                {
                  pattern: /^1\d{10}$/,
                  message: '手机号格式错误！',
                },
              ]}
            />
            <ProFormCaptcha
              fieldProps={{
                size: 'large',
                prefix: (
                  <LockOutlined
                    style={{
                      color: token.colorText,
                    }}
                    className={'prefixIcon'}
                  />
                ),
              }}
              captchaProps={{
                size: 'large',
              }}
              placeholder={'请输入验证码'}
              captchaTextRender={(timing, count) => {
                if (timing) {
                  return `${count} ${'获取验证码'}`;
                }
                return '获取验证码';
              }}
              name="captcha"
              rules={[
                {
                  required: true,
                  message: '请输入验证码！',
                },
              ]}
              onGetCaptcha={async () => {
                message.success('获取验证码成功！验证码为：1234');
              }}
            />
          </>
        )}

        {
          loginType === 'account' && 
          <div
          style={{
            marginBlockEnd: 24,
          }}
        >
          <ProFormCheckbox noStyle name="autoLogin">
            自动登录
          </ProFormCheckbox>
          {/* <a
            style={{
              float: 'right',
            }}
          >
            忘记密码
          </a> */}
        </div>
        }
        
      </LoginFormPage>
          
      <Modal
        open={isModalOpen}
        title="设置密码"
        maskClosable={false}
        keyboard={false}
        width={'50%'}
        classNames={{
          body:styles.tc_lg_1,
          footer:styles.tc_lg_2,
        }}
        onOk={handleOk}
        onCancel={handleCancel}
        footer={[
          <Button key="submit" type="primary" className={styles.tc_lg_2_1} loading={loading} onClick={handleOk}>
            确定
          </Button>
        ]}
      >
        <p className={styles.tc_lg_1_1}>初次登录系统，请设置密码：</p>
        <Form {...formItemLayout} form={formLogin} name="form_in_modal" initialValues={{ remember: true }}>
          <Form.Item
            name="password"
            label="新密码"
            hasFeedback
            rules={[{ required: true, message: '请输入新密码!' }, {
              min: 6,
              message: '至少六位数',
            },]}
          >
            <Input.Password  placeholder='请输入至少6位(不区分大小写)的新密码'/>
          </Form.Item>
          <Form.Item
            name="confirm"
            label="确认新密码"
            dependencies={['password']}
            hasFeedback
            rules={[
              {
                required: true,
                message: '请再次输入您的新密码!',
              },
              {
                min: 6,
                message: '至少六位数',
              },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('password') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('您输入的新密码不匹配!'));
                },
              }),
            ]}
          >
            <Input.Password  placeholder='请重复输入新密码'/>
          </Form.Item>
         
        
        </Form>
      </Modal>
    </div>
  );
};

export default () => {
  return (
    <ProConfigProvider dark>
      <Page />
    </ProConfigProvider>
  );
};